import React, { useEffect, useState } from 'react'
import ReactDom from 'react-dom'
import './index.scss'

const CreateToast = ({ message, position, cb }) => {
  const morePosition = position.split('-').join(' ')
  const [className, setClassname] = useState(`app-toast ${morePosition}`) // show

  useEffect(() => {
    const timer = setTimeout(() => {
      setClassname('app-toast')
      cb()
    }, 1500)

    return () => {
      clearTimeout(timer)
    }
  }, [cb])

  return (
    <div className={className}>
      <div className="info">{message}</div>
    </div>
  )
}

const Toast = (params) => {
  const div = document.createElement('div')
  let message = ''
  let position = ''
  let callback = null
  let cb = null
  div.className = 'app-toast-wrap'
  document.body.appendChild(div)

  const removeDom = () => {
    ReactDom.unmountComponentAtNode(div)
    document.body.removeChild(div)
  }

  if (typeof params === 'object') {
    message = params.message
    position = params.position
    callback = params.callback
    cb = () => {
      callback && callback()
      removeDom()
    }
  } else {
    message = params
    position = 'top-right'
    callback = () => {}
  }

  ReactDom.render(
    React.createElement(CreateToast, {
      message,
      position,
      cb,
    }),
    div,
  )
}

export default Toast
